package com;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName="PromissionFilter",urlPatterns="/*")


public class PromissionFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换成Http
        HttpServletRequest hsr = (HttpServletRequest) servletRequest;
        HttpServletResponse hsp = (HttpServletResponse) servletResponse;
        //获取标记
        String flag = (String)hsr.getSession().getAttribute("flag");
        //获取过滤地址
        String sPath = hsr.getServletPath();

        //指定规则
        if(sPath != null && (sPath.equals("/LoginServlet") ||
                sPath.equals("/index.jsp") || sPath.equals("/VerifyLoginServlet")))
        {
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            if(flag != null && flag.equals("login_success"))
            {
                filterChain.doFilter(servletRequest,servletResponse);
            }
            else if(flag != null && flag.equals("login_fail"))
            {
                hsr.getSession().setAttribute("msg","登录失败，请重新登录");
                hsr.getRequestDispatcher("index.jsp").forward(hsr,hsp);
            }
            else
            {
                hsr.getSession().setAttribute("msg","没有登录，请先登录");
                hsr.getRequestDispatcher("index.jsp").forward(hsr,hsp);
            }

        }
    }

    @Override
    public void destroy() {

    }
}
